<?php
require_once(__DIR__."/DbCommand.class.php");
class Db{
    public $host;
    public $user;
    public $password;
    public $dbname;
    public $raw;
    public $error;
    public $affected_count;
    public function __construct($host,$user,$password,$dbname){
        $this->host = $host;
        $this->user= $user;
        $this->password = $password;
        $this->dbname = $dbname; 
    }
    function open(){
        $this->raw = mysqli_connect($this->host, $this->user, $this->password, $this->dbname);
        $this->error = $this->raw->connect_errno;
        if(!$this->error) {
            $this->raw->select_db($this->dbname);
            $this->error = $this->raw->error;
        }
        return $this;
    }
    function close(){
        $this->raw->close();return $this;
    }
    function beginTrans(){
        $this->begin_transaction();
        $this->error = $this->raw->error;
        return $this;
    }
    function commit(){
        $this->commit(); 
        $this->error = $this->raw->error;
        return $this;
    }
    function rollback(){
        $this->rollback(); 
        $this->error = $this->raw->error;
        return $this;
    }
    function execute($sql){
        $rs = $this->raw->query($sql);
        $this->affected_count = $this->raw->$affected_rows;
        $this->error = $this->raw->error;
        return $rs;
    }
    function query($sql,$oop=false){
        $rs = $this->raw->query($sql);
        if(!$rs) {$this->error = $this->raw->error; return null;}
        $results= array();
        if($oop){
            while ($row = $rs->fetch_object()) $results[] = $row;
        }else {
            while ($row = $rs->fetch_assoc()) $results[] = $row;
        }
        return $results;
    }
    function first($sql,$oop=false){
        $rs = $this->raw->query($sql);
        if(!$rs) {$this->error = $this->raw->error; return null;}
        
        if($oop){
            return $rs->fetch_object();
        }else {
            return $rs->fetch_assoc();
        }
        
    }

    function createCommand($sql){
        return new DbCommand($this->raw->prepare($sql),$sql);
    }

    static function create(){
        return new Db("localhost","root","","YE");
    }
}